{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 反转有向图\n",
    "\n",
    "![Asked by Facebook](https://img.shields.io/badge/Asked%20by-Facebook-important?style=social&logo=facebook)\n",
    "\n",
    "&emsp;&emsp;给定一张有向图，给出所有边方向反转的“全逆有向图”。\n",
    "\n",
    "```text\n",
    " In[1]: A->B, B->C, A->C\n",
    "Out[1]: B->A, C->B, C->A\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from collections import defaultdict"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Node:\n",
    "    def __init__(self, value):\n",
    "        self.adjacent = []\n",
    "        self.value = value"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def reverseGraph(graph: dict) -> dict:\n",
    "    reverse = {key: Node(key) for key in graph.keys()}\n",
    "    for key in graph.keys():\n",
    "        for node in graph[key].adjacent:\n",
    "            reverse[node.value].adjacent.append(graph[key].value)\n",
    "    return reverse"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = Node('a')\n",
    "b = Node('b')\n",
    "c = Node('c')\n",
    "\n",
    "a.adjacent += [b, c]\n",
    "b.adjacent += [c]\n",
    "\n",
    "graph = {\n",
    "    a.value: a,\n",
    "    b.value: b,\n",
    "    c.value: c\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a: []\n",
      "b: ['a']\n",
      "c: ['a', 'b']\n"
     ]
    }
   ],
   "source": [
    "for key, value in reverseGraph(graph).items():\n",
    "    print(key, value.adjacent, sep=': ')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
